package com.nowcoder.community.service;

import com.nowcoder.community.dao.LoginTicketMapper;
import com.nowcoder.community.dao.UserMapper;
import com.nowcoder.community.entity.LoginTicket;
import com.nowcoder.community.entity.User;
import com.nowcoder.community.util.CommunityConstant;
import com.nowcoder.community.util.CommunityUtil;
import com.nowcoder.community.util.MailClient;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;

@Service
public class UserService implements CommunityConstant {

    @Autowired
    private UserMapper userMapper;
    @Autowired
    private LoginTicketMapper loginTicketMapper;

    @Autowired
    private MailClient mailClient;
    @Autowired
    private TemplateEngine templateEngine;
    @Value("${community.path.domain}")
    private String domain;
    @Value("${server.servlet.context-path}")
    private String contextPath;

    public User findUserById(int id) {
        return userMapper.selectById(id);
    }

    //注册
    public Map<String , Object> register(User user){
        Map<String , Object> map = new HashMap<>();

        // 判空
        if(user == null) throw new IllegalArgumentException("参数不能为空!");
        if(StringUtils.isBlank(user.getUsername())){
            map.put("usernameMsg","账号不能为空");
            return map;
        }
        if(StringUtils.isBlank(user.getPassword())){
            map.put("passwordMsg","密码不能为空");
            return map;
        }

        // 去重
        User u = userMapper.selectByName(user.getUsername());
        if(u != null){
            map.put("usernameMsg","该账号已存在!");
            return map;
        }
        u = userMapper.selectByEmail(user.getEmail());
        if(u != null){
            map.put("emailMsg","该邮箱已被注册!");
            return map;
        }

        //用户注册     有salt的原因就是黑客不能轻易的推断出 password和hash码的对应关系,即使是同一个password因为salt的原因也是不同的hash码(自动扩大密钥空间)
        user.setSalt(CommunityUtil.generateUUID().substring(0,5)); //注: 数据库中存的是 salt 和 hash码 ,没有存明文密码.
        user.setPassword(CommunityUtil.md5(user.getPassword() + user.getSalt()));
        user.setType(0);
        user.setStatus(0);
        user.setActivationCode(CommunityUtil.generateUUID());
        user.setHeaderUrl(String.format("http://images.nowcoder.com/header/%dt.png",new Random().nextInt(1000)));// 头像
        user.setCreateTime(new Date());
        userMapper.insertUser(user);

        // 发送激活邮件
        Context context = new Context();
        context.setVariable("email",user.getEmail());
        String url = domain + contextPath + "/activation/" + user.getId() + "/" + user.getActivationCode();
        context.setVariable("url",url);
        String content = templateEngine.process("/mail/activation",context);
        mailClient.sentMail(user.getEmail() ,"激活账号", content);

        // 注册成功的话map应该是空的
        return map;
    }

    /**激活*/
    public int activation(int userId , String code){
        // status: 0-未激活 1-已激活
        User user = userMapper.selectById(userId);
        if(user.getStatus() == 1) return ACTIVATION_REPEAT;
        if( !user.getActivationCode().equals(code) ) return ACTIVATION_FAIL;
        userMapper.updateStatus(userId , 1);
        return ACTIVATION_SUCCESS;
    }

    /**登录*/
    public Map<String , Object> login(String username ,String password , int expiredSeconds){
        HashMap<String, Object> map = new HashMap<>();

        //空值处理
        if(StringUtils.isBlank(username)){
            map.put("usernameMsg","账号不能为空!");
            return map;
        }
        if(StringUtils.isBlank(password)){
            map.put("passwordMsg","密码不能为空");
            return map;
        }
        //验证账号
        User user = userMapper.selectByName(username);
        if(user == null){
            map.put("usernameMsg", "该账号不存在!");
            return map;
        }
        //验证激活状态
        if (user.getStatus() == 0){
            map.put("usernameMsg","该账号未激活!");
            return map;
        }
        //验证密码
        password = CommunityUtil.md5(password+user.getSalt());
        if(!user.getPassword().equals(password)){
            map.put("passwordMsg","密码不正确!");
            return map;
        }
        // 生成登录凭证
        LoginTicket loginTicket = new LoginTicket();
        loginTicket.setUserId(user.getId());
        loginTicket.setTicket(CommunityUtil.generateUUID());
        loginTicket.setStatus(0);
        loginTicket.setExpired(new Date(System.currentTimeMillis() + expiredSeconds*1000));
        loginTicketMapper.insertLoginTicket(loginTicket);

        map.put("ticket",loginTicket.getTicket());
        return map;
    }

    /**退出登录*/
    public void logout(String ticket){ // 通常情况都是改状态而不是直接删除 , 留一份保底数据
        loginTicketMapper.updateStatus(ticket , 1);
    }

    /**根据ticket字符串查询一条登录记录*/
    public LoginTicket findLoginTicket(String ticket){
        return loginTicketMapper.selectByTicket(ticket);
    }

    /**上传头像*/
    public int updateHeader(int userId , String headerUrl){
        return userMapper.updateHeader(userId , headerUrl);
    }
}
